package com.zhanggm.zyk.pay.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.bw.zhanggm.file.config.AjaxResult;
import com.zhanggm.zyk.pay.config.AlipayConfig;
import com.zhanggm.zyk.pay.entity.Order;
import com.zhanggm.zyk.pay.entity.PaymentApp;
import com.zhanggm.zyk.pay.service.IOrderService;
import com.zhanggm.zyk.pay.service.IPaymentAppService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/pay/")
public class PayController {

    @Autowired
    IPaymentAppService iPaymentAppService;

    @Autowired
    IOrderService iOrderService;

    /**
     * 下单接口
     *  查询订单信息
     *  调用支付宝下单接口
     *  保存交易单号到本地订单
     * @return 支付的表单信息
     */
    @DSTransactional
    @GetMapping("alipay/getOrderForm")
    public String getOrderForm(String id) throws AlipayApiException {
        //查询订单信息
        PaymentApp paymentApp = iPaymentAppService.getById(id);
        //调用支付宝下单接口
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,AlipayConfig.merchant_private_key,"json","GBK",AlipayConfig.alipay_public_key,"RSA2");
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //异步接收地址，仅支持http/https，公网可访问
        request.setNotifyUrl("");
        //同步跳转地址，仅支持http/https
        request.setReturnUrl(AlipayConfig.return_url);
        /******必传参数******/
        JSONObject bizContent = new JSONObject();
        //商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", paymentApp.getId()+"");
        //支付金额，最小值0.01元
        bizContent.put("total_amount", paymentApp.getThisApplicationAmount());
        //订单标题，不可使用特殊符号
        bizContent.put("subject", paymentApp.getSupplierName());
        //电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request,"POST");
        // 如果需要返回GET请求，请使用
        // AlipayTradePagePayResponse response = alipayClient.pageExecute(request,"GET");
        String pageRedirectionData = response.getBody();
        log.info(pageRedirectionData);
        if(response.isSuccess()){
            log.info(pageRedirectionData);
            //修改业务表状态
            paymentApp.setPaymentStatus("Rejected");
            iPaymentAppService.saveOrUpdate(paymentApp);
            //添加订单表，记录支付状态
            Order order = new Order().setBusinessId(paymentApp.getId() + "")
                    .setCreationTime(LocalDateTime.now())
                    .setPaymentAmount(paymentApp.getThisApplicationAmount())
                    .setPaymentStatus("yizhifu")
                    .setThirdPartyOrderId(response.getTradeNo());

            iOrderService.saveOrUpdate(order);
        }
        return pageRedirectionData;
    }

    @Autowired
    private HttpServletRequest request;

    @RequestMapping("call")
    public AjaxResult call() throws AlipayApiException {
        Map<String, String> dataMap = ServletUtil.getParamMap(request);
        log.info("checkData:{}",dataMap);

        boolean checkV1 = AlipaySignature.rsaCheckV1(dataMap, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
        log.info("AlipaySignature.rsaCheckV1:{}", checkV1);
        if (!checkV1) {
            AjaxResult.error("签名失败");
        }

        if (checkV1 && StrUtil.equalsIgnoreCase(dataMap.get("trade_status"), AlipayConfig.TRADE_SUCCESS)) {
            System.out.println("调用成功");
            //修改订单
            PaymentApp paymentApp = iPaymentAppService.getById(dataMap.get("out_trade_no"));
            paymentApp.setPaymentStatus("Paid");
            iPaymentAppService.saveOrUpdate(paymentApp);
        }

        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl,AlipayConfig.app_id,AlipayConfig.merchant_private_key,"json","GBK",AlipayConfig.alipay_public_key,"RSA2");
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{" +
                "  \"out_trade_no\":\""+dataMap.get("out_trade_no")+"\"," +
                "  \"trade_no\":\""+dataMap.get("trade_no")+"\"," +
                "  \"query_options\":[" +
                "    \"trade_settle_info\"" +
                "  ]" +
                "}");
        AlipayTradeQueryResponse response = alipayClient.execute(request);

        if(response.isSuccess()){
            System.out.println("调用成功");
            //修改订单
            PaymentApp paymentApp = iPaymentAppService.getById(dataMap.get("out_trade_no"));
            paymentApp.setPaymentStatus("Paid");
            iPaymentAppService.saveOrUpdate(paymentApp);
        }
        return AjaxResult.success();
    }
}
